<?
$PACKAGES_DESCR_FILE = "https://www.domain.se/repository/dists/stable/main/packages";

function installremove()
{
	global $PACKAGES_DESCR_FILE;

	$newpkg_avalible = false;
	unset($_SESSION['packman']);

	$pkg_list = @parse_ini_file($PACKAGES_DESCR_FILE, true);
	if( count($pkg_list) == 0 ) {
		echo '<b style="color:#f00">Lyckades inte ansluta till programservern.</b><br><br>';
	}
	else {
		foreach( $pkg_list AS $pkgname => $pkg ) {
			$vbuf = array();
			
			$_SESSION['packman'][$pkgname]['installed'] = false;
			$_SESSION['packman'][$pkgname]['mandatory'] = false;
			if( isset($pkg['Mandatory']) )
				$_SESSION['packman'][$pkgname]['mandatory'] = true;
			if( isset($pkg['Also_remove']) )
				$_SESSION['packman'][$pkgname]['also_remove'] = $pkg['Also_remove'];

			exec('dpkg -s '.$pkgname.' 2> /dev/null', $vbuf);
			$vbuf = implode("\n", $vbuf);
			if( preg_match('/^Status: install ok installed$/m', $vbuf) ) {
				preg_match('/^Version: (\S*)$/m', $vbuf, $matchver);
				$_SESSION['packman'][$pkgname]['installed'] = true;
				$pkg_list[$pkgname]['Installed'] = 1;
				$pkg_list[$pkgname]['LocalVersion'] = $matchver[1];
				if( $pkg_list[$pkgname]['LocalVersion'] != $pkg_list[$pkgname]['Version'] ) {
					$newpkg_avalible = true;
				}
			}
		}
	}
		

	if( $newpkg_avalible ) {
		echo '<b style="color:#f00">En eller flera program är ouppdaterade.</b><br>';
		echo "<input type=\"submit\" name=\"b_unow\" value=\"Uppgradera Nu\" class=\"buttonlong\" / ".help('update_button')."><br><br>";
	}


	echo '
		<table><tr><td>
		<table style="border:solid #ccc;border-width:0px 1px 0px 1px">
		<tr><td colspan="5" class="tbhead">Tillgängliga program</td></tr>
		<tr><td class="tbhead">Namn</td><td class="tbhead">Installerad version</td><td class="tbhead">Tillgänglig version</td><td class="tbhead">Vald</td></tr>
	';

	if( $pkg_list !== false ) {
		foreach( $pkg_list AS $pkgname => $pkg ) {
			echo '<tr><td style="vertical-align:top;border-bottom:1px solid #ccc" onMouseOver="helpbox_start(\''.htmlentities($pkg['Description'], ENT_COMPAT, 'UTF-8').'\')" onMouseOut="helpbox_stop()"><b>'.$pkg['Name'].'&nbsp;</b></td>';
			echo '<td style="text-align:center;vertical-align:top;border-bottom:1px solid #ccc">'.(isset($pkg['LocalVersion'])?htmlentities($pkg['LocalVersion'], ENT_COMPAT, 'UTF-8'):'&nbsp;').'</td>';
			echo '<td style="text-align:center;vertical-align:top;border-bottom:1px solid #ccc">'.htmlentities($pkg['Version'], ENT_COMPAT, 'UTF-8').'</td>';

			echo '<td style="text-align:center;vertical-align:top;border-bottom:1px solid #ccc"><input type="checkbox" name="pkgchecked'.$pkgname.'" '.($pkg['Mandatory'] == 1 && $pkg['Installed'] == 1?'checked disabled':'').' '.($pkg['Installed'] == 1?'checked':'').'></td></tr>';
		}
	}
	echo '</table></td></tr>';
	echo '<tr><td style="text-align:right"><input class="buttonlong" type="submit" name="b_aptget" value="Utför ändringar" style=""></td><tr>';
	echo '</table><br>';
	echo '<a href="?s=packman&amp;t=proglist" style="float: right;height:0em;font-size:70%;color:#00f;">Lista installerade deb-paket</a>';

}


function show_aptrunning()
{
	echo '<b>Uppdatering av programvara</b><br>';
	echo '<div id="text"><img src="/images/loading.gif">Program installeras, tas bort eller uppdateras...</div><br><br>';
	echo '<b onClick="switchhidden(\'apt_stat\')" style="color:#0c0">Visa status &gt;&gt;</b><div id="apt_stat" style="font-size:70%;background-color:#ccc;display:none">hämtar status...</div></div><br>';
	echo '
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
<!--
function stathandler( xmlHttp , id ) {
	var re = new RegExp(/\^Done!/);
	var reError = new RegExp(/Exiting with error \(\d+\)/);
	var response = xmlHttp.responseText;

	if( response.match(re) ) {
		response = response.replace(/\^Done!/, "");
		document.getElementById( id ).innerHTML = response;
		if( response.match(reError) )
			document.getElementById( "text" ).innerHTML = "Avslutades med fel";
		else
			document.getElementById( "text" ).innerHTML = "Installationen är klar";
	}
	else {
		document.getElementById( id ).innerHTML = response;
	}
}

function stat_update() {
	ajax_send( "ajax.php", "jsfunc", stathandler, "getaptstat", "apt_stat");
	setTimeout("stat_update()", 300);
}
setTimeout("stat_update()", 100);
-->
</SCRIPT>
	';
}


function upgrade()
{
	/*
	UPPGRADERINGAR
	läser sträng från cron.d/upgrade
	*/
	echo '<table '.help('update_auto').'><tr><td class="tbhead">Automatiska uppdateringar</td></tr><tr><td>';
	if( file_exists("/etc/cron.d/upgrade") ) {
		$crons = explode(" ",@file_get_contents("/etc/cron.d/upgrade"));
		echo "<input type=\"checkbox\" name=\"autoupdate\" onClick=\"upgrade_update()\" checked> Automatiska uppdateringar<br>\n";
	}
	else {
		echo "<input type=\"checkbox\" name=\"autoupdate\" onClick=\"upgrade_update()\"> Automatiska uppdateringar<br>\n";
	}
	echo "<table>";
	echo "<tr ".help('update_auto')."><td>uppgradera</td><td>";
		$out = "<select name=\"day\">
			<option value=*>Alla dagar
			<option value=mon>Måndagar
			<option value=tue>Tisdagar
			<option value=wed>Onsdagar
			<option value=thu>Torsdagar
			<option value=fri>Fredagar
			<option value=sat>Lördagar
			<option value=sun>Söndagar
			</select>
		";
		echo str_replace('value='.$crons[4].'>','selected value='.$crons[4].'>', $out);
	echo "</td><td>klockan ";
		$out = "<select name=\"hour\">
			<option value=1>01:00
			<option value=2>02:00
			<option value=3>03:00
			<option value=4>04:00
			<option value=5>05:00
			<option value=6>06:00
			<option value=7>07:00
			<option value=8>08:00
			<option value=9>09:00
			<option value=10>10:00
			<option value=11>11:00
			<option value=12>12:00
			<option value=13>13:00
			<option value=14>14:00
			<option value=15>15:00
			<option value=16>16:00
			<option value=17>17:00
			<option value=18>18:00
			<option value=19>19:00
			<option value=20>20:00
			<option value=21>21:00
			<option value=22>22:00
			<option value=23>23:00
			<option value=24>24:00
			<option value=\"*\">Varje timme
		";
	echo str_replace('value='.$crons[1].'>','selected value='.$crons[1].'>', $out);	
	echo "</td></tr>";
	echo "</table>\n";
	echo '
<script type="text/javascript">
<!--
function upgrade_update() {
	if( document.pageform.autoupdate.checked ) {
		document.pageform.day.disabled = false
		document.pageform.hour.disabled = false
	}
	if( !document.pageform.autoupdate.checked ) {
		document.pageform.day.disabled = true
		document.pageform.hour.disabled = true
	}
}
upgrade_update()
-->
</script>
';
	echo '</td></tr></table><br>';
}


function settings()
{
	$user = '';
	$passwd = '';
	$apt_sources = file_get_contents('/etc/apt/sources.list');

	if( $apt_sources !== false ) {
		if( preg_match('#^deb\W+https://([^:]+):([^@]+)@www\.domain\.se/repository#m', $apt_sources, $matches) ) {
			$user = $matches[1];
			$passwd = $matches[2];
		}
	}

	echo '<table><tr><td class="tbhead" colspan="2">Kontouppgifter för programserver</td></tr>';
	echo '<tr><td>Användare:</td><td><input name="username" type="text" value="'.$user.'"></td></tr>';
	echo '<tr><td>Lösenord:</td><td><input name="password" type="password" value="'.$passwd.'"></td></tr>';
	echo '</table><br>';
}


function proglist()
{
	exec('dpkg -l', $buf);
	echo '<table>';
	echo '<tr><td class="tbhead">Paketnamn</td><td class="tbhead">Beskrivning</td><td class="tbhead">Installerad ver</td><td class="tbhead">Tillgänglig ver</td></tr>';
	foreach( $buf AS $line ) {
		if( preg_match('/^ii\s*(\S*)\s*(\S*)\s*(.*)$/', $line, $match) ) {
			$vbuf = array();
			exec('apt-cache show '.$match[1].' | grep -e "^Version: "', $vbuf);
			preg_match('/^Version: (.*)$/', $vbuf[0], $matchver);
			echo '<tr style="font-size:70%"><td>'.htmlentities($match[1]).'</td><td>'.htmlentities($match[3]).'</td><td>'.htmlentities($matchver[1]).'</td><td>'.htmlentities($match[2]).'</td></tr>';
		}
	}
	echo '</table><br>';
}



////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////

	$packman_menu = array(
		array('installremove', 'Lägg till / Ta bort program'), 
		array('upgrade', 'Automatiska uppdateringar'), 
		array('settings', 'Inställningar') 
	);

	switch( $_GET['t'] ) {
	default:
	case 'installremove':
		html_start( $packman_menu );
		exec('pgrep -f "/apt_install_wwwadmin "', $duh, $runningAptInstall);
		exec('pgrep -f "/apt_upgrade_wwwadmin "', $duh, $runningAptUpgrade);
                $runningAptInstall = !$runningAptInstall;
                $runningAptUpgrade = !$runningAptUpgrade;
		if( $runningAptInstall || $runningAptUpgrade)
			show_aptrunning();
		else
			installremove();
		html_end();
		break;
	case 'upgrade':
		html_start( $packman_menu );
		upgrade();
		html_end( true, true, true );
		break;
	case 'settings':
		html_start( $packman_menu );
		settings();
		html_end(true, true, true);
		break;
	case 'proglist':
		html_start( $packman_menu );
		proglist();
		html_end();
		break;
	}
?>
